package com.ve.everything;

import com.ve.everything.helper.EverythingHelper;
import com.ve.everything.pojo.EverythingFilePojo;
import com.ve.everything.pojo.Responsejson;
import com.ve.everything.searcher.DocumentWithHighlights;
import com.ve.everything.searcher.LuceneSearch;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

import static com.ve.everything.searcher.LuceneSearch.searchFile;

@RestController
public class MainController {
    @RequestMapping(path = "api/searchByString")
    @ResponseBody
    public Responsejson searchByString(String searchString) throws Exception {
        Responsejson result = new Responsejson();
        /*try{
            List<EverythingFilePojo> everythingFilePojos = EverythingHelper.getInstance().searchFilePojo(searchString);
            result.setData(everythingFilePojos);
            result.setCount(everythingFilePojos.size());
        }catch (Exception e){
            result.setCode(2);
            result.setMsg(e.getMessage());
        }*/
        List<EverythingFilePojo> resultList = searchFile(searchString);
        result.setData(resultList);
        result.setCount(resultList.size());
        return result;
    }

    @RequestMapping(path = "api/loadfile")
    @ResponseBody
    public String loadFile(String filename,String filepath) throws Exception {
        StringBuffer xml = new StringBuffer();
//        Path path = Paths.get(filepath + File.separator + filename);
        Path path = Paths.get(filepath);
        List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
        lines.forEach(str -> xml.append(str).append("\r\n"));
        return xml.toString();
    }

    @RequestMapping(path = "api/savefile")
    @ResponseBody
    public Responsejson saveFile(String filename,String filepath,String content)throws Exception {
        Path path = Paths.get(filepath + File.separator + filename);
        Files.write(path, content.getBytes(StandardCharsets.UTF_8));
        Responsejson responsejson = new Responsejson();
        return responsejson;
    }
}
